<template>
  <div class="head-container">
    <el-input v-model="searchName" class="mb-20px" clearable placeholder="请输入考试或班级名称">
      <template #prefix>
        <Icon icon="ep:search" />
      </template>
    </el-input>
  </div>
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="treeData"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      :default-expanded-keys="defaultExpandedKeys"
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
    >
      <template #default="{ node, data }">
        <el-tooltip 
          :content="node.label" 
          placement="top" 
          :show-after="500"
          :disabled="node.label.length <= 10"
        >
          <span class="custom-tree-node">
            <Icon 
              :icon="data.type === 'exam' ? 'ep:document' : 'ep:user-filled'" 
              class="mr-5px" 
            />
            <span class="tree-node-label">{{ node.label }}</span>
            <span v-if="data.type === 'exam'" class="text-gray-400 text-sm ml-5px">
              ({{ data.examDate }})
            </span>
          </span>
        </el-tooltip>
      </template>
    </el-tree>
  </div>
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import { ExamTestApi, ExamTestTreeVO } from '@/api/system/examtest'
import { formatDate } from '@/utils/formatTime'

defineOptions({ name: 'ExamScoreTree' })

interface TreeNode {
  id: string
  label: string
  type: 'exam' | 'class'
  examId?: number
  classId?: number
  examDate?: string
  studentCount?: number
  children?: TreeNode[]
}

const searchName = ref('')
const treeData = ref<TreeNode[]>([])
const treeRef = ref<InstanceType<typeof ElTree>>()
const defaultExpandedKeys = ref<string[]>([]) // 默认展开的节点

const defaultProps = {
  children: 'children',
  label: 'label'
}

/** 从班级名称中提取数字用于排序 */
const extractClassNumber = (className: string): number => {
  // 尝试匹配括号中的数字，如：高三(1)班 -> 1
  const match = className.match(/\((\d+)\)/)
  if (match && match[1]) {
    return parseInt(match[1], 10)
  }
  
  // 如果没有括号格式，尝试匹配所有数字
  const numberMatch = className.match(/\d+/)
  if (numberMatch) {
    return parseInt(numberMatch[0], 10)
  }
  
  // 如果没有数字，返回一个大数值，让它排在后面
  return 999999
}

/** 班级排序函数 */
const sortClassNodes = (nodes: TreeNode[]): TreeNode[] => {
  return nodes.sort((a, b) => {
    const numA = extractClassNumber(a.label)
    const numB = extractClassNumber(b.label)
    
    // 先按数字排序
    if (numA !== numB) {
      return numA - numB
    }
    
    // 数字相同则按字符串排序
    return a.label.localeCompare(b.label, 'zh-CN')
  })
}

/** 获取树形数据 */
const getTreeData = async (autoSelectFirst = false) => {
  try {
    // 调用新的树形列表接口
    const examTreeList: ExamTestTreeVO[] = await ExamTestApi.getExamTestTreeList()
    
    // 构建树形结构
    const treeNodes: TreeNode[] = []
    
    for (const exam of examTreeList) {
      const examNode: TreeNode = {
        id: `exam_${exam.id}`,
        label: exam.examName,
        type: 'exam',
        examId: exam.id,
        examDate: exam.examDate ? formatDate(exam.examDate, 'YYYY-MM-DD') : '',
        children: []
      }
      
      // 为每个考试添加班级节点
      if (exam.classList && exam.classList.length > 0) {
        for (const classItem of exam.classList) {
          const classNode: TreeNode = {
            id: `class_${exam.id}_${classItem.classId}`,
            label: classItem.className,
            type: 'class',
            examId: exam.id,
            classId: classItem.classId,
            studentCount: classItem.studentCount
          }
          
          examNode.children!.push(classNode)
        }
        
        // 对班级节点按数字排序
        examNode.children = sortClassNodes(examNode.children!)
      }
      
      treeNodes.push(examNode)
    }
    
    treeData.value = treeNodes
    
    // 设置默认展开第一个考试节点
    if (treeNodes.length > 0) {
      defaultExpandedKeys.value = [treeNodes[0].id]
    }
    
    // 如果需要自动选择第一个节点且有数据
    if (autoSelectFirst && treeNodes.length > 0) {
      // 等待DOM更新后设置默认选择
      await nextTick()
      const firstExamNode = treeNodes[0]
      // 设置当前选中节点
      treeRef.value?.setCurrentKey(firstExamNode.id)
      // 触发节点点击事件
      handleNodeClick(firstExamNode)
    }
  } catch (error) {
    console.error('获取树形数据失败:', error)
  }
}

/** 基于名字过滤 */
const filterNode = (name: string, data: TreeNode) => {
  if (!name) return true
  return data.label.includes(name)
}

/** 处理节点被点击 */
const handleNodeClick = async (data: TreeNode) => {
  emits('node-click', {
    type: data.type,
    examId: data.examId,
    classId: data.classId,
    label: data.label
  })
}

const emits = defineEmits(['node-click'])

/** 监听搜索名称 */
watch(searchName, (val) => {
  treeRef.value!.filter(val)
})

/** 设置默认选择第一个考试 */
const setDefaultSelection = async () => {
  if (treeData.value.length > 0) {
    await nextTick()
    const firstExamNode = treeData.value[0]
    // 设置默认展开第一个考试节点
    defaultExpandedKeys.value = [firstExamNode.id]
    // 设置当前选中节点
    treeRef.value?.setCurrentKey(firstExamNode.id)
    // 触发节点点击事件
    handleNodeClick(firstExamNode)
  }
}

/** 初始化 */
onMounted(async () => {
  // 加载树形数据并自动选择第一个考试节点
  await getTreeData(true)
})

/** 暴露刷新方法和设置默认选择方法 */
defineExpose({
  refresh: getTreeData,
  loadTree: getTreeData,
  setDefaultSelection
})
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
  overflow: hidden;
}

.tree-node-label {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}
</style>
